<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\MajorRequest;
use App\Models\V1\Major;
use App\Models\V1\NewArrival;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Log;
use Auth;

class MajorsController extends Controller
{
    /**
     * 显示班级数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $codes = $this->getEnrollmentCodes();
        $data['codes'] = $codes;
        $arrival_code = $this->getArrivalCodes();
        $data['arrival_code'] = $arrival_code;
        return view('v1.newData.major', $data);
    }

    /**
     * 获取志愿数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的班级数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');

        $reqParams = $request->all();
        $year = isset($reqParams['year']) ? $reqParams['year'] : '';

        $arrival_code = $request->get('arrival_code');

        $from_select = $request->get('from_select');

        if ($from_select == false && empty($arrival_code)) {
            $arrival_code = $this->getArrivalCodes();
        }
        // 获取符合查询条件的班级数据
        $data = $this->getMajorList($currentPage, $rows, $arrival_code, $year);

        $formatList = array();

        if (!$data->isEmpty()) {
            $count = $data->total() > 0 ? $data->total() : 0;
            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    //专业代码
                    $code = $item['code'];
                    $arrival_code = $item['arrival_code'];
                    $parent_code = $item['parent_code'];
                    if ($parent_code != 0) {
                        //招生目录
                        $parent_major = $this->getMajorByCode($parent_code, $arrival_code);
                        $formatItem['parent_code'] = $parent_major['code'];
                        $formatItem['parent_name'] = $parent_major['name'];
                        $formatItem['min_number'] = $parent_major['min_number'];
                        $formatItem['max_number'] = $parent_major['max_number'];
                    } else {
                        $formatItem['parent_code'] = '';
                        $formatItem['parent_name'] = '';
                        $formatItem['min_number'] = '';
                        $formatItem['max_number'] = '';
                    }
                    $formatItem['major_code'] = $item['code'];
                    $formatItem['major_name'] = $item['name'];
                    $formatItem['arrival_code'] = $arrival_code;
                    $formatItem['count'] = $item['count'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }
                $response['msg'] = '加载数据成功';
            }
        } else {
            $count = 0;
            $formatList = [];
            $response['msg'] = '暂无数据';
        }
        $response['code'] = 0;
        $response['count'] = $count;
        $response['data'] = $formatList;
        return $response;
    }

    /**
     * 进入单条班级数据显示界面（适用于新增addData、编辑editData、查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        switch ($request->input('view')) {
            case 'addData':
                $majors = $this->getParentMajors();
                $data['parentMajors'] = $majors;
                Log::info('par', ['pa' => $majors]);
                return view('v1.form.major_item', $data);
                break;
            case 'viewData':
                $code = $request->input('code');
                $arrival_code = $request->input('arrival_code');
                $major = $this->getMajorByCode($code, $arrival_code);
                $parent_major = $this->getMajorByCode($major['parent_code'], $arrival_code);
                $data['major'] = $major;
                $data['parent_major'] = $parent_major;
                return view('v1.form.major_item', $data);
        }
    }

    /**
     * 显示志愿数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser->getAttribute('code');

        return view('v1.form.upload_excel', $data);
    }


    /**
     * 新增基本信息
     *bail关键字表示只要第一个验证失败后面就不验了，提高效率
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $type = $request->get('type');
        $response = [
            'rspStatus' => false,
            'rspMsg' => '志愿[' . $request->get('code') . '],新增失败！',
        ];
        if ($request->method() === 'POST') {
            // 验证请求

            //添加招生目录
            if ($type == 1) {
                $rules['code'] = 'bail|required';
                $rules['name'] = 'bail|required';
                $rules['min_number'] = 'bail|required';
                $rules['max_number'] = 'bail|required';
                $rules['captcha'] = 'bail|required|captcha';
                $messages['code.required'] = '招生目录代码不能为空';
                $messages['name.required'] = '招生目录名称不能为空';
                $messages['min_number.required'] = '至少填报志愿数不能为空';
                $messages['max_number.required'] = '至多填报志愿数不能为空';
                $messages['captcha.captcha'] = '验证码错误';
                $this->validate($request, $rules, $messages);
            } elseif ($type == 2) {
                //新增专业
                $rules['code'] = 'bail|required';
                $rules['name'] = 'bail|required';
                $rules['parent_code'] = 'bail|required';
                $rules['count'] = 'bail|required';
                $rules['captcha'] = 'bail|required|captcha';
                $messages['code.required'] = '专业代码不能为空';
                $messages['name.required'] = '专业名称不能为空';
                $messages['parent_code.required'] = '所属招生目录不能为空';
                $messages['count.required'] = '专业招生计划人数不能为空';
                $messages['captcha.captcha'] = '验证码错误';
                $this->validate($request, $rules, $messages);
            }
            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '志愿[' . $request->get('code') . '],新增成功！';
            }
        }

        return $response;
    }

    /**
     * 删除班级基本信息
     *
     * @param NewArrivalRequest $request
     * @return array
     */
    public function deleteData(MajorRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '专业代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateMajor($request);

            // 删除班级信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '专业代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除班级基本信息
     *
     * @param Request $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '专业批量删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '专业批量删除成功！';
            }
        }

        return $response;
    }


    /**
     * 更新报到流程基本信息(单元格)
     *
     * @param MajorRequest $request
     * @return array
     */
    public function updateCellData(MajorRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '专业代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateMajor($request);
            // 更新部门信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '专业代码[' . $request->input('code') . '],更新成功！';
            }
        }
        return $response;
    }


    /***
     * 处理添加
     * @param Request $request
     * @return mixed
     */
    public function handleAdd(Request $request)
    {
        $arrival_code = $this->getArrivalCodes();
        $type = $request->get('type');
        if ($type == 1) {
            // 拼装新增数据数组
            $insertData = [
                'code' => $request->get('code'),
                'name' => $request->input('name'),
                'parent_code' => 0,
                'min_number' => isset($request['min_number']) ? $request->input('min_number') : '',
                'max_number' => isset($request['max_number']) ? $request->input('max_number') : '',
                'arrival_code' => $arrival_code,
            ];
        } elseif ($type == 2) {
            // 拼装新增数据数组
            $insertData = [
                'code' => $request->input('code'),
                'name' => $request->input('name'),
                'parent_code' => isset($request['parent_code']) ? $request->input('parent_code') : '',
                'count' => $request['count'],
                'arrival_code' => $arrival_code,
            ];
        }
        $rspObj = Major::updateOrCreate(['code' => $request->input('code')], $insertData);
        return $rspObj;
    }


    /****
     * @param Request $request
     * @param $bCell 是否为单元格修改数据
     * @return mixed
     */
    public function handleUpdate(Request $request, $bCell)
    {
        $code = $request->input('code');
        $arrival_code = $request->input('arrival_code');
        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                if ($attr === 'major_name') {
                    $updateData['name'] = $values[$counter];
                }
                $counter++;
            }
        }
        $rspObj = Major::where('code', $code)
            ->where('arrival_code', $arrival_code)
            ->update($updateData);

        return $rspObj;
    }



    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的迎新列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getMajorList($page, $rows, $keywords, $year)
    {
        if ($year != '') {
            if (!isset($keywords) || empty($keywords)) {
                $data = Major::orderBy('created_at', 'desc')
                    ->where('parent_code', '!=', '0')
                    ->where('created_at', 'like', '%' . $year . '%')
                    ->paginate($rows, ['*'], 'page', $page);
            } else {
                $data = Major::where('arrival_code',$keywords)
                    ->where('parent_code', '!=', '0')
                    ->orderBy('created_at', 'desc')
                    ->where('created_at', 'like', '%' . $year . '%')
                    ->paginate($rows, ['*'], 'page', $page);
            }
        } else {
            if (!isset($keywords) || empty($keywords)) {
                $data = Major::orderBy('created_at', 'desc')
                    ->where('parent_code', '!=', '0')
                    ->paginate($rows, ['*'], 'page', $page);
            } else {
                $data = Major::where('arrival_code',$keywords)
                    ->where('parent_code', '!=', '0')
                    ->orderBy('created_at', 'desc')
                    ->paginate($rows, ['*'], 'page', $page);
            }
        }

        return $data;
    }


    /***
     * 获取所有招生目录
     */
    private function getParentMajors()
    {
        $arrival_code = $this->getArrivalCodes();
        $majors = Major::where('parent_code', 0)->where('arrival_code', $arrival_code)->select('code', 'name')->get();
        return $majors;
    }

    /***
     * 根据code获取专业信息
     * @param $code
     * @return mixed
     */
    private function getMajorByCode($code, $arrival_code)
    {
        $major = Major::where('code', $code)->where('arrival_code', $arrival_code)->first();
        return $major;
    }

    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCodes()
    {
        $code = '';
        $years = NewArrival::where('isOn', true)->first();
        if (!empty($years) || isset($years)) {
            $code = $years->code;
        }
        return $code;
    }

    /**
     * 获取所有招生年份
     *
     * @param $code
     * @return mixed|string
     */
    private function getEnrollmentCodes()
    {
        $codes = NewArrival::all()->pluck('code')->toArray();
        return $codes;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新班级信息验证请求
     *
     * @param Request $request
     */
    private function validateMajor(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新班级信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');
        $arrival_codes = $request->input('arrival_code');
        if ($bBatch) { // 批量删除
            for ($i = 0; $i < count($where); $i++) {
                $code = $where[$i];
                $arrival_code = $arrival_codes[$i];
                $rspObj = Major::where('code', $code)
                    ->where('arrival_code', $arrival_code)
                    ->delete();
            }
        } else { // 单条删除
            $rspObj = Major::where('code', $where)
                ->where('arrival_code', $arrival_codes)
                ->delete();
        }

        return $rspObj;
    }

    /**
     * 格式化显示发布信息
     *
     * @param $val
     * @return string
     */
    private function formateIsShowData($val)
    {
        $strFormat = '<span class="layui-bg-gray">否</span>';
        if ($val) {
            $strFormat = '<span class="layui-bg-green">是</span>';
        }
        return $strFormat;
    }

}
